<!--充电桩产品-->
<template>
  <div class="app-container" style="background: #f2f2f2" v-loading="loading"
       element-loading-background="rgba(255, 255, 255, 0.3)">
    <el-row :gutter="10">
      <!-- 左侧下拉 -->
      <el-col :span="4">
        <el-card shadow="never" :body-style="{height:'calc( 100vh - 126px)'}">
          <div slot="header">
            <span>产品类型</span>
            <el-button style="float: right; padding: 3px; margin-left: 5px" icon="el-icon-delete"
                       @click="handleDeleteCategory"></el-button>
            <el-button style="float: right; padding: 3px; margin-left: 5px" icon="el-icon-edit"
                       @click="handleUpdateCategory"></el-button>
            <el-button style="float: right; padding: 3px; margin-left: 5px" icon="el-icon-plus"
                       @click="handleAddCategory"></el-button>
          </div>
          <el-tree ref="tree" node-key="id" :data="categoryList" :props="{label: 'categoryName'}"
                   @node-click="handleNodeClick"></el-tree>
        </el-card>
      </el-col>
      <!-- 右侧内容 -->
      <el-col :span="20">
        <el-card shadow="never" :body-style="{height:'calc( 100vh - 126px)'}">
          <div slot="header">
            <span>产品参数</span>
            <el-button style="float: right; padding: 3px 10px; margin: 0 15px" type="success" icon="el-icon-plus"
                       @click="handleAddProduct">新增
            </el-button>
          </div>
          <el-table :data="productList" border>
            <el-table-column label="序号" type="index" width="50" align="center"/>
            <el-table-column label="产品编号" prop="productId" align="center"/>
            <el-table-column label="产品名称" prop="productName" align="center"/>
            <el-table-column label="充电枪数量" prop="portNum" align="center"/>
            <el-table-column label="终端类型" align="center">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.current_type" :value="scope.row.terminalType"/>
              </template>
            </el-table-column>
            <el-table-column label="额定功率" align="center">
              <template slot-scope="scope">{{scope.row.ratedPower + 'W'}}</template>
            </el-table-column>
            <el-table-column label="设备厂商" prop="producer" align="center"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateProduct(scope.row)"
                  v-hasPermi="['station:product:edit']"
                >修改
                </el-button>

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteProduct(scope.row)"
                  v-hasPermi="['station:product:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 添加或修改产品对话框 -->
          <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="padding: 0 80px 0 50px">
              <el-form-item label="产品编号" prop="productId">
                <el-input v-if="form.$tag === 'edit_product'" v-model="form.productId" :disabled="true"/>
                <el-cascader ref="cascader" v-if="form.$tag === 'add_product'" v-model="form.productId" :props="props"
                             :show-all-levels="false"
                             placeholder="请选择产品编号">
                  <template slot-scope="{ node, data }">
                    <span style="float: left; margin-right: 15px">{{ data.name }}</span>
                    <span
                      style="float: right; color: #8492a6; font-size: 13px; margin-left: 15px">{{ data.value }}</span>
                  </template>
                </el-cascader>
                <!--                <el-select v-model="form.productId" placeholder="请选择产品编号" :disabled="this.form.$tag !== 'add_product'">-->
                <!--                  <el-option-->
                <!--                    v-for="item in iotProductList"-->
                <!--                    :key="item.id"-->
                <!--                    :label="item.productName"-->
                <!--                    :value="item.id">-->
                <!--                  </el-option>-->
                <!--                </el-select>-->
              </el-form-item>
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="form.productName" placeholder="请输入产品名称"/>
              </el-form-item>
              <el-form-item label="充电枪数量" prop="portNum">
                <el-input v-model="form.portNum" placeholder="请输入充电枪数量" maxlength="1"
                          oninput="value=value.replace(/[^0-9]/g,'')"/>
              </el-form-item>
              <el-form-item label="终端类型" prop="terminalType">
                <el-select v-model="form.terminalType" placeholder="请选择终端类型" clearable>
                  <el-option
                    v-for="dict in dict.type.current_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="额定功率(W)" prop="ratedPower">
                <el-input v-model="form.ratedPower" placeholder="请输入额定功率" oninput="value=value.replace(/[^0-9]/g,'')"/>
              </el-form-item>
              <el-form-item label="设备厂商" prop="producer">
                <el-input v-model="form.producer" placeholder="请输入设备厂商"/>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitProductForm">确 定</el-button>
              <el-button @click="open = false">取 消</el-button>
            </div>
          </el-dialog>

          <!-- 添加或修改品类对话框 -->
          <el-dialog :title="title" :visible.sync="openCategory" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rulesCategory" label-width="120px">
              <el-form-item label="产品类型标识" prop="categoryMark">
                <el-input v-model="form.categoryMark" placeholder="请输入产品类型标识"/>
              </el-form-item>
              <el-form-item label="产品类型名称" prop="categoryName">
                <el-input v-model="form.categoryName" placeholder="请输入产品类型名称"/>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFormCategory">确 定</el-button>
              <el-button @click="openCategory = false">取 消</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import { queryProduct } from '@/api/iot/product'
  import { listOfCategoryId, add, edit, del } from '@/api/smart/device/product'
  import { listCategory, getCategory, delCategory, addCategory, updateCategory } from '@/api/iot/category'

  export default {
    name: 'station_product',
    dicts: ['current_type'],
    data() {
      return {
        props: {
          lazy: true,
          lazyLoad: this.lazyLoadIotProduct
        },
        // 遮罩层
        loading: false,
        //品类列表
        categoryList: [],
        // 充电桩产品列表
        productList: [],
        // 物联产品列表
        iotProductTree: [],
        current_category: null,
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        openCategory: false,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          productId: { required: true, message: '请选择产品编号', trigger: 'blur' },
          productName: { required: true, message: '请输入产品名称', trigger: 'blur' },
          portNum: { required: true, message: '请输入充电枪数量', trigger: 'blur' },
          terminalType: { required: true, message: '请选择终端类型', trigger: 'blur' },
          ratedPower: { required: true, message: '请输入额定功率', trigger: 'blur' },
          producer: { required: true, message: '请输入设备厂商', trigger: 'blur' }
        },
        rulesCategory: {
          categoryMark: { required: true, message: '请输入产品类型标识', trigger: 'blur' },
          categoryName: { required: true, message: '请输入产品类型名称', trigger: 'blur' }
        }
      }
    },
    watch: {
      current_category(val) {
        if (this.$refs.cascader) {
          this.$refs.cascader.panel.lazyLoad()
        }
      }
    },
    created() {
      this.getCategoryList()
    },
    methods: {
      //获取产品列表
      getProductList() {
        this.loading = true
        listOfCategoryId(this.current_category.id).then(response => {
          this.productList = response.data
        }).finally(() => {
          this.loading = false
        })
      },
      //获取品类列表
      async getCategoryList() {
        this.loading = true
        await listCategory(/*{ parentId: 31 }*/).then(response => {
          this.categoryList = response.data
          this.iotProductTree = this.categoryList.map(item => ({
            name: item.categoryName,
            label: item.id,
            value: item.id,
            children: item.children,
            leaf: false
          }))
          if (this.categoryList.length !== 0) {
            this.current_category = this.categoryList[0]
          }
        }).finally(() => {
          this.loading = false
        })
        if (this.current_category == null) return
        this.getProductList()
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys([this.current_category.id])
        })
      },
      //点击品类
      handleNodeClick(node) {
        this.current_category = node
        this.getProductList()
      },
      //新增产品
      handleAddProduct() {
        this.reset()
        this.form.$tag = 'add_product'
        this.title = '新增产品'
        this.open = true
      },
      //修改产品
      handleUpdateProduct(row) {
        this.form = Object.assign({}, row)
        this.form.$tag = 'edit_product'
        this.title = '修改产品'
        this.open = true
      },
      //删除产品
      handleDeleteProduct(row) {
        const productId = row.productName
        this.$modal.confirm('是否确认删除产品名称为"' + productId + '"的数据项？').then(function() {
          return del(row.id)
        }).then(() => {
          this.getProductList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      },
      //提交产品表单
      submitProductForm() {
        let param = this.form
        if (param.productId instanceof Array) {
          param.productId = param.productId.pop()
        }
        this.$refs['form'].validate(valid => {
          if (!valid) return
          switch (this.form.$tag) {
            case 'edit_product':
              edit(param).then(res => {
                this.$modal.msgSuccess('修改产品成功')
                this.open = false
                this.getProductList()
              })
              break
            case 'add_product':
              add(param).then(res => {
                this.$modal.msgSuccess('新增产品成功')
                this.open = false
                this.getProductList()
              })
              break
          }
        })
      },
      //物联产品加载
      lazyLoadIotProduct(node, resolve) {
        const { level } = node
        if (node.level === 0) {
          resolve(this.iotProductTree.filter((item) => item.value === this.current_category.id))
        } else {
          queryProduct({ categoryId: node.value }).then(res => {
            resolve(Array.from(res.data).map(item => ({
              name: item.productName,
              label: item.id,
              value: item.id,
              leaf: true
            })))
          })
        }
      },
      //重置表单
      reset() {
        this.form = {}
      },

      /********************************品类操作*******************************/
      /** 新增按钮操作 */
      handleAddCategory() {
        this.reset()
        /*this.form.parentId = 31*/
        this.form.parentId = this.current_category.id
        this.openCategory = true
        this.title = '添加产品类型'
      },
      /** 修改按钮操作 */
      handleUpdateCategory() {
        this.reset()
        getCategory(this.current_category.id).then(response => {
          this.form = response.data
          this.openCategory = true
          this.title = '修改产品类型'
        })
      },
      /** 提交按钮 */
      submitFormCategory() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateCategory(this.form).then(response => {
                this.$modal.msgSuccess('修改产品类型成功')
                this.openCategory = false
                this.getCategoryList()
              })
            } else {
              addCategory(this.form).then(response => {
                this.$modal.msgSuccess('新增产品类型成功')
                this.openCategory = false
                this.getCategoryList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDeleteCategory() {
        let id = this.current_category.id
        this.$modal.confirm('是否确认删除类型名称为"' + this.current_category.categoryName + '"的数据项？').then(function() {
          return delCategory(id)
        }).then(() => {
          this.getCategoryList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      }
    }
  }
</script>

